package com.mnt.washio.utils.network.ws;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.activities.PricingActivity;
import com.mnt.washio.objects.Product;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class GetPricingListWSControl extends BaseWSControl {
	private String zipCode;
	private PricingActivity mPriceAct;
	
	public GetPricingListWSControl(Context context,
			WebServiceCommunicatorListener listener, String zipCode) {
		super(context, listener, WebServiceFlag.GET_PRICING);
		this.zipCode = zipCode;
		mPriceAct = (PricingActivity)context;
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.ADMIN_WS_URL + "prices/byzip/" + zipCode;

		try {
			String respone = NetworkUtils.doRequest(url);
			try {
				JSONObject jsonObject = new JSONObject(respone);

				mPriceAct.deliverFeeMaximum = Statics.getString(jsonObject, "deliverFeeMaximum");
				mPriceAct.deliveryFee = Statics.getString(jsonObject, "deliveryFee");
				mPriceAct.orderMinimum = Statics.getString(jsonObject, "orderMinimum");
				
				return getUsersFromJSONArray(jsonObject.getJSONArray("items"));
			} catch (JSONException e) {
				mError = e.getMessage();
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<Product> getUsersFromJSONArray(JSONArray proJSonArray)
			throws JSONException {
		ArrayList<Product> products = new ArrayList<Product>();
		for (int i = 0; i < proJSonArray.length(); i++) {
			JSONObject userJSONObject = proJSonArray.getJSONObject(i);
			Product p = new Product();
			p.setId(userJSONObject.getString("objectId"));
			p.setTitle(userJSONObject.getString("title"));
			p.setPrice(userJSONObject.getString("price"));
			p.setCategory(userJSONObject.getString("category"));

			products.add(p);
		}

		return products;
	}
}
